package tool

import (
	"encoding/json"
	"math/rand"
	"regexp"
	"strings"
	"time"
)

var r *rand.Rand

type cookieInfo struct {
	Key   string `json:"Key"`
	Value string `json:"Value"`
}

func CookieArrToStr(jsonStr string) (cookieStr string, err error) {
	var data []cookieInfo
	err = json.Unmarshal([]byte(jsonStr), &data)
	if err != nil {
		return
	}
	for _, v := range data {
		cookieStr += v.Key + "=" + v.Value + ";"
	}

	return
}

// 请求间隔
func GetRandomMillSecondNum() time.Duration {
	//step1: 设置种子数
	rand.Seed(time.Now().UnixNano())
	//step2：获取随机数
	return time.Duration(rand.Intn(1000) + 500) //[500,1500) 500ms - 1500ms
}

// 任务间隔
func GetRandomMinuteNum() time.Duration {
	//step1: 设置种子数
	rand.Seed(time.Now().UnixNano())
	//step2：获取随机数
	return time.Duration(rand.Intn(5) + 30) //35 - 35分钟
}

func Html2Text(str string) string {
	deepStr := str
	//将HTML标签全转换成小写
	re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
	deepStr = re.ReplaceAllStringFunc(deepStr, strings.ToLower)

	//去除STYLE
	re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
	deepStr = re.ReplaceAllString(deepStr, "")

	//去除SCRIPT
	re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
	deepStr = re.ReplaceAllString(deepStr, "")

	//去除所有尖括号内的HTML代码，并换成换行符
	re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
	deepStr = re.ReplaceAllString(deepStr, "\n")

	//去除连续的换行符
	re, _ = regexp.Compile("\\s{2,}")
	deepStr = re.ReplaceAllString(deepStr, "\n")

	deepStr = strings.Replace(deepStr, "&rdquo;", `"`, -1)
	deepStr = strings.Replace(deepStr, "&ldquo;", `"`, -1)
	deepStr = strings.Replace(deepStr, "&middot;", `.`, -1)
	deepStr = strings.Replace(deepStr, "&lt;", `<`, -1)
	deepStr = strings.Replace(deepStr, "&gt;", `>`, -1)
	deepStr = strings.Replace(deepStr, "&nbsp;", ` `, -1)

	return strings.TrimSpace(deepStr)
}

//获取传入时间的上一周的开始和结束日期
func GetLastWeekIntervalTime(dateDay string) (startTime, endTime string) {
	now, err := time.Parse("2006-01-02", dateDay)
	if err != nil {
		return
	}
	week := -1
	offset := int(time.Monday - now.Weekday())
	//周日做特殊判断 因为time.Monday = 0
	if offset > 0 {
		offset = -6
	}

	year, month, day := now.Date()
	thisWeek := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
	startTime = thisWeek.AddDate(0, 0, offset+7*week).Format("2006-01-02")
	endTime = thisWeek.AddDate(0, 0, offset+6+7*week).Format("2006-01-02")

	return startTime, endTime
}

func RandomStr(n int) string {
	bytes := make([]byte, n)
	for i := 0; i < n; i++ {
		b := r.Intn(26) + 65
		bytes[i] = byte(b)
	}
	return string(bytes)
}
